package com.summer.dao;

import java.util.List;
import java.util.Map;

import com.google.common.collect.Lists;

public class UserDao {

	public boolean add(User user) {
		String sql = "insert into t_user (name, password, age, sex) values (?, ?, ?, ?)";
		return ConnectDB.executeUpdate(sql, user.getName(), user.getPassword(), user.getAge(), user.getSex());
	}

	public boolean delete(long id) {
		String sql = "delete from t_user where id = ?";
		return ConnectDB.executeUpdate(sql, id);
	}

	public boolean update(User user) {
		String sql = "update t_user set name = ?,age = ?,sex = ? where id = ?";
		return ConnectDB.executeUpdate(sql, user.getName(), user.getAge(), user.getSex(), user.getId());
	}
	
	public User queryByName(String name) {
		String sql = "select * from t_user where name = ?";
		return User.from(ConnectDB.executeQuery(sql, name).get(0));
	}
	
	public User queryById(long id) {
		String sql = "select * from t_user where id = ?";
		return User.from(ConnectDB.executeQuery(sql, id).get(0));
	}
	
	public List<User> queryAll() {
		String sql = "select * from t_user";
		List<Map<String, Object>> dataList = ConnectDB.executeQuery(sql);
		List<User> userList = Lists.newArrayList();
		for(Map<String, Object> data : dataList) {
			userList.add(User.from(data));
		}
		return userList;
	}
	
	public static void main(String[] args) {
		UserDao dao = new UserDao();
		User user = new User("liuwen", "liuwen12", "女", 20);
		dao.add(user);
		System.out.println(user);
		System.out.println("==============================================================");
		user = dao.queryByName(user.getName());
		user.setAge(21);
		dao.update(user);
		System.out.println(user);
		System.out.println("==============================================================");
		List<User> userList = dao.queryAll();
		System.out.println(userList);
	}
}
